package com.bl.es;

import com.bl.utils.ESClientUtil;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;

public class EsTest {

    @Test
    public void patch() throws Exception {
        // 1.获取ES连接
        TransportClient client = ESClientUtil.getClient();
        // 2.创建批量操作对象
        BulkRequestBuilder bulk = client.prepareBulk();
        // 3.批量创建文档，放入批量操作对象中
        for (int i = 2; i < 100; i++) {
            IndexRequestBuilder builder = client.prepareIndex("pethome", "user", i + "").setSource(
                    XContentFactory.jsonBuilder()
                            .startObject()
                            .field("id", i - 1)
                            .field("name", "我在源码学习Java!" + i)
                            .field("age", i - 1)
                            .field("sex", i%2)
                            .endObject()
            );
            BulkResponse result = bulk.add(builder).get();
            System.out.println(result.status());
        }
        // 4.关闭连接
        client.close();
    }


    /**
     *  中和案例
     *  - 查询用户表
     *  name包含：我在源码
     *  age在1~12之间
     *  - sex=1
     *  - 每页大小2
     * - 从2页开始查
     *    - 按照age倒序
     */

    @Test
    public void test1() throws Exception {
        TransportClient client = ESClientUtil.getClient();

        SearchRequestBuilder pethome = client.prepareSearch("pethome");
        // 得到bool对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();


        // 设置must-match条件
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "我在源码");
        boolQueryBuilder.must(matchQueryBuilder);


        // 设置filter条件

        boolQueryBuilder
                .filter(QueryBuilders.termQuery("sex",1))
                .filter(QueryBuilders.rangeQuery("age").gte(1).lte(12));
        pethome.setQuery(boolQueryBuilder);



        // 设置分页数据
        pethome.setSize(2);
        pethome.setSize(2);
        // 根据age 排序
        pethome.addSort("age", SortOrder.DESC);

        SearchHit[] hits = pethome.get().getHits().getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsMap());


        }

        client.close();
    }





}
